import axios from "axios";
import router from '@/router/index';

const requestFile = (url, options) => {
    // 创建 axios 实例
    const service = axios.create({
        baseURL: "http://localhost:5173/api/", // api base_url
        changeOrigin: true,
        timeout: 6000 // 请求超时时间
    });
    // 请求拦截
    service.interceptors.request.use(config => {
        // 这里可设置请求头等信息
        config.headers['Content-Type'] = 'multipart/form-data';
        config.responseType = 'blob';
        if (options && options.body) {
            config.data = options.body;
        }
        //对get请求解码,防止出现400
        if (config.params != undefined && config.params != '') {
            let url = config.url + '?';
            let keys = Object.keys(config.params);
            for (let key of keys) {
                url += `${key}=${encodeURIComponent(config.params[key])}&`;
            }
            url = url.slice(0, -1);
            config.params = {};
            config.url = url;
        }
        return config;
    });

    // 返回拦截
    service.interceptors.response.use(response => {

        // 这里可进行返回数据的格式化等操作
        return response.data;
    }, (err) => {
        if (err.response.status == 404) {
            localStorage.removeItem("token");
            router.push('/login');
        }
        const data = {
            message: err.response.data.message || '请重试',
            code: err.response.status !== 200 ? err.response.status : err.response.data.errCode
        }
        throw data;
    }
    );

    return service(url, options);

}



export default requestFile;